package com.sjf.JavaNIO.filelock;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * FileLockDemo
 *
 * @author huangtang
 * @since 2022/4/14 18:03
 **/
public class FileLockDemo1 {
    public static void main ( String[] args ) throws Exception {
        String str = "hello,sjf";
        System.out.println ("str :" + str);
        //创建缓冲区并写入数据
        ByteBuffer buffer = ByteBuffer.wrap (str.getBytes (StandardCharsets.UTF_8));
        //创建文件通道
        String filePath = "D:\\atguigu\\01.txt";
        Path path = Paths.get (filePath);
        FileChannel channel = FileChannel.open (path ,
                                                StandardOpenOption.READ);
        //修改文件指针以便后续在末尾追加内容
        channel.position (channel.size () - 1);
        //加锁，如果加共享锁在上面创建文件通道时，必须指明READ方式，而不能指定Write方式，否则会报错
        FileLock lock = channel.lock (0L , Long.MAX_VALUE , true);

        System.out.println ("is Shared?" + lock.isShared ());
        //将缓冲区的数据写入通道
        //channel.write (buffer);
        channel.close ();

        //读文件
        readFile (filePath);
    }

    /**
     * 读取文件
     *
     * @param filePath 文件路径
     * @throws Exception
     */
    private static void readFile ( String filePath ) throws Exception {
        FileReader fileReader = new FileReader (filePath);
        BufferedReader bufferedReader = new BufferedReader (fileReader);
        String tr = bufferedReader.readLine ();
        System.out.println ("读取出内容：");
        while (tr != null) {
            System.out.println ("" + tr);
            tr = bufferedReader.readLine ();
        }
        fileReader.close ();
        bufferedReader.close ();
    }

}
